package com.specialtreasure.freightdepot.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.core.activity.BaseNewActivity;
import com.app.core.config.Constants;
import com.app.core.config.HttpApi;
import com.app.core.util.ApkUtil;
import com.app.core.util.AppManager;
import com.specialtreasure.freightdepot.R;
import com.specialtreasure.freightdepot.fragment.GoodsInfoFragment;
import com.specialtreasure.freightdepot.fragment.InformationTodayFragment;
import com.specialtreasure.freightdepot.fragment.MeFragment;
import com.specialtreasure.freightdepot.fragment.PublicFragmentV2;
import com.specialtreasure.freightdepot.fragment.ShareCarFragment;
import com.specialtreasure.freightdepot.model.BaseModel;
import com.specialtreasure.freightdepot.model.ClientUpdateInfo;
import com.specialtreasure.freightdepot.mq.MQUtils;
import com.vondear.rxtools.RxAppUtils;
import com.yanzhenjie.httpmodule.http.CallServer;
import com.yanzhenjie.httpmodule.http.Result;
import com.yanzhenjie.httpmodule.http.StringRequest;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.List;

/**
 * Created by Administrator on 2017/8/7 0007.
 * 主页面
 */

public class MainActivity extends BaseNewActivity {
    public static final String TAG = "MainActivity";

    private long exitTime = 0;
    private Fragment[] fragments;
    private int index, currentTabIndex;
    private RadioGroup rg_tab_bottom;
    //    private PublicFragment publicFragment = new PublicFragment();

    private GoodsInfoFragment goodsInfoFragment=new GoodsInfoFragment();//货源信息
    private ShareCarFragment shareCarFragment = new ShareCarFragment();//我的车库
    private PublicFragmentV2 publicFragment = new PublicFragmentV2();//第二版发布
    private MeFragment meFragment = new MeFragment();//个人中心
    private InformationTodayFragment informationFragment = new InformationTodayFragment();//信息管理


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_main);
        initView();
        setData();
        getPermission();
        updateVersion();
    }


    private void setData() {
        //初始化Fragment显示
        fragments = new Fragment[]{goodsInfoFragment,shareCarFragment, publicFragment, informationFragment, meFragment};
        getSupportFragmentManager().beginTransaction().add(R.id.fl_content, fragments[2]).show(fragments[2]).commitAllowingStateLoss();
        index=2;
        currentTabIndex=2;

        //radiogruop点击事件
        rg_tab_bottom.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_tab_goods://货源信息
                        index = 0;
                        break;
                    case R.id.rb_tab_carport://车库
                        index = 1;
                        break;
                    case R.id.rb_tab_public://发布
                        index = 2;
                        break;
                    case R.id.rb_tab_information://信息管理
                        index = 3;
                        break;
                    case R.id.rb_tab_me://我的
                        index = 4;
                        break;
                    default:
                        break;
                }
                // 重置按钮状态
                if (currentTabIndex != index) {
                    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                    fragmentTransaction.hide(fragments[currentTabIndex]);

                    if (!fragments[index].isAdded() && !fragments[index].isDetached()) {
                        fragmentTransaction.add(R.id.fl_content, fragments[index]);
                    }

                    fragmentTransaction.show(fragments[index]).commitAllowingStateLoss();
                    currentTabIndex = index;
                }
            }

        });


    }



    private void initView() {
        rg_tab_bottom = (RadioGroup) findViewById(R.id.rg_tab_bottom);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            //两秒之内按返回键就会退出
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                AppManager.getAppManager().AppExit(this);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }




    @Override
    public String getActiviyName() {
        return TAG;
    }

    /**
     * 版本更新
     */
    private void updateVersion() {
        String url = Constants.HTTP_URL + HttpApi.UPDATEVERSION;
        StringRequest request = new StringRequest(url, RequestMethod.POST);
        request.add("platformType", 1);//1、android 2、pc
        request.add("userType", 2);//1、车主 2、企业

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);
        CallServer.getInstance().request(Constants.ZERO, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                String result = response.get().getResult();
                Logger.e("请求成功：" + result);

                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject != null) {
                    Integer status = jsonObject.getInteger("status");
                    String msg = jsonObject.getString("msg");

                    if (status != null && status == 0) {
                        ClientUpdateInfo data = JSON.parseObject(jsonObject.getJSONObject("data").toString(), ClientUpdateInfo.class);
                        if (data != null) {
                            Integer onlineVersionCode = data.getVersionCode();
                            int localVersionCode = RxAppUtils.getAppVersionCode(mContext);

                            if (onlineVersionCode != null && onlineVersionCode > localVersionCode) {
                                showForceUpdateDialog(MainActivity.this, data);
                            }

                        }

                    } else {
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();

                    }

                }


            }
        });

    }

    /**
     * 显示弹窗
     *
     * @param context
     * @param version
     */
    public void showForceUpdateDialog(Context context, final ClientUpdateInfo version) {
        new AlertDialog.Builder(context)
                .setTitle("您的版本过低，请更新后重试")
                .setMessage(version.getUpdateMessage())
                .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                    @Override

                    public void onClick(DialogInterface dialog, int which) {
                        downloadFile(version.getPackageAddress().trim());
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Process.killProcess(Process.myPid());
                    }
                })
                .setCancelable(false)
                .create()
                .show();
    }

    /**
     * 下载文件
     *
     * @param url
     */
    private void downloadFile(final String url) {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);
        RequestParams requestParams = new RequestParams(url);
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            requestParams.setSaveFilePath(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/zhuangxian.apk");
            x.http().get(requestParams, new Callback.ProgressCallback<File>() {
                @Override
                public void onWaiting() {

                }

                @Override
                public void onStarted() {
                }

                @Override
                public void onLoading(long total, long current, boolean isDownloading) {
                    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    progressDialog.setMessage("亲，努力下载中。。。");
                    progressDialog.show();
                    progressDialog.setMax((int) total);
                    progressDialog.setProgress((int) current);
                }

                @Override
                public void onSuccess(File result) {
                    Toast.makeText(mContext, "下载成功", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                    ApkUtil.install(MainActivity.this, result);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    ex.printStackTrace();
                    Toast.makeText(mContext, "下载失败，请检查网络和SD卡", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                }

                @Override
                public void onCancelled(CancelledException cex) {
                }

                @Override
                public void onFinished() {
                }
            });
        } else {
            Toast.makeText(mContext, "请插入SD卡后重试", Toast.LENGTH_SHORT).show();
        }
    }



    /**
     * 多权限申请
     */
    private void getPermission() {
        AndPermission.with(this)
                .permission(Permission.CAMERA, Permission.PHONE, Permission.LOCATION, Permission.STORAGE) // 多个权限组。
                .requestCode(300)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> list) {
                        // TODO do something...
                        if (requestCode == 300) {
//                            AndPermission.defaultSettingDialog(MainActivity.this, 400).show();
                        }
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> list) {
                        // TODO 用户没有同意授权，一般弹出Dialog让用户去Setting中授权。
                        if (requestCode == 300) {
                        }
                    }
                })
                .start();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // 自己记录fragment的位置,防止activity被系统回收时，fragment错乱的问题
        // super.onSaveInstanceState(outState);
        outState.putInt("currentTabIndex", currentTabIndex);
    }


    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // super.onRestoreInstanceState(savedInstanceState);
        currentTabIndex = savedInstanceState.getInt("currentTabIndex");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MQUtils.stopMQ(mContext);
    }
}
